const child_process = require('child_process')
const os = require('os')
const shell = 'C:\\Program Files\\Git\\git-bash.exe'
const fs = require('fs')
const path = require('path')

function getIP() {
  const cardInfos = os.networkInterfaces()
  for (card in cardInfos) {
    if (['WLAN', '本地连接', '以太网'].includes(card)) {
      const infos = cardInfos[card]
      const ipInfo = infos.find(info => info.family.toUpperCase() === 'IPV4')
      if (ipInfo) {
        return ipInfo.address
      }

      console.warn('could not find matched ip')
      return 'localhost'
    }
  }
}

function dateFormat(date = new Date(), needTime = false) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  const d2 = str => (str + '').length < 2  ? ('00' + str).slice(-2) : str
  const datePart = [year, month, day].map(d2).join('-')
  const timePart = needTime ? ' ' + [hour, minute, second].map(d2).join(':') : ''

  return datePart + timePart
}

function writeLog(content, filename='') {
  const fpath = path.join('logs', filename || dateFormat() + '.log')
  fs.writeFile(fpath, content, { flag: 'a'}, (err) => {
    if (err) {
      console.log('writeLog err:', err)
    }
  } )
}

function accessLog(content) {
  writeLog(content, 'access.log')
}

function createLog (prefix = 'LOG') {
  return (...args) => {
    writeLog([`[${prefix.toUpperCase()}]`, ...args].join(' '))
  }
}

function createCLog (prefix = 'LOG') {
  return (...args) => console.log(`[${prefix.toUpperCase()}]`, ...args)
}

function spawnChild (cmd, args = [], dataCb = console.log, doneCb = console.log) {
  const child = child_process.spawn(cmd, args, {/* shell, */ maxBuffer: 10 * 1024 * 1024})
  const log = createLog('spawn child')

  child.stdout.on('data', (data) => {
    log('stdout-data >>', data.toString())
    dataCb(data.toString())
  })

  child.stderr.on('data', (data) => {
    log('stderr-data >>', data.toString())
    dataCb(data.toString())
  })

  child.stdout.on('end', () => {
    log('stdout-end !!')
  })

  child.stderr.on('end', () => {
    log('stderr-end !!')
  })

  child.on('exit', code => {
    log('child exit !!!')
    doneCb('<br /> <br /> EXIT CODE IS: ' + code + '  执行' + ( code > 0 ? '失败' : '成功'))
  })

  child.on('error', (err) => {
    log('child error ', err)
    doneCb(err.message + err.stack)
  })

  return child
}


module.exports = {
  getIP,
  createLog,
  createCLog,
  spawnChild,
  dateFormat,
  accessLog,
}